package com.market.service.impl;

import com.market.common.exception.ServiceException;
import com.market.common.vo.ResponseCode;
import com.market.entity.Units;
import com.market.mapper.UnitsMapper;
import com.market.service.UnitsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UnitsServiceImpl implements UnitsService {
    @Resource
    UnitsMapper unitsMapper;

    /**
     * 添加
     * @param unitsName
     * @return
     * @throws ServiceException
     */
    @Override
    public int addUnits(String unitsName) throws ServiceException {
        List<Units> units = unitsMapper.selects();
        int count = 0;
        for (Units unit : units) {
            if (unit.getCommodityUnitsName() != unitsName) {
                int insert = unitsMapper.insert(unitsName);
                if (insert > 0) {
                    count = insert;
                    throw new ServiceException(ResponseCode.SUCCESS);
                } else {
                    throw new ServiceException(ResponseCode.ERROR);
                }
            } else {
                throw new ServiceException(ResponseCode.ERROR);
            }
        }

        return count;
    }

    /**
     * 删除
     * @param unitsId
     * @return
     * @throws ServiceException
     */
    @Override
    public int deleteUnits(Integer unitsId) throws ServiceException {
        int delete = unitsMapper.delete(unitsId);
        if (delete > 0) {
            throw new ServiceException(ResponseCode.SUCCESS);
        } else {
            throw new ServiceException(ResponseCode.ERROR);
        }
    }

    /**
     * 修改
     * @param unitsId
     * @param unitsName
     * @return
     * @throws ServiceException
     */
    @Override
    public int update(Integer unitsId, String unitsName) throws ServiceException {
        int update = unitsMapper.update(unitsId, unitsName);
        if (update > 0) {
            throw new ServiceException(ResponseCode.SUCCESS);
        } else {
            throw new ServiceException(ResponseCode.ERROR);
        }
    }

    /**
     * 单位搜索功能
     *
     * @param namesOrId
     * @return
     */
    @Override
    public List<Units> searchClasses(String namesOrId) throws ServiceException {
        List<Units> units = unitsMapper.selectNamesOrId(namesOrId);
        if (units.size() > 0) {
            return units;
        } else {
            throw new ServiceException(ResponseCode.ERROR);
        }
    }
}
